﻿#include "customstatusbar.h"
#include "common.h"
#include "EagleDeviceMgr.h"
#include "QPen"
#include "QPainter"
#include "ConfigFile.h"
#include "qtlogger.h"
#include <QMutexLocker>
#include <QMutex>
#include "EagleMainFrame.h"

#define EAGLE_STATUS_BAR_NORMAL 0
#define EAGLE_STATUS_BAR_WAIT 1
static const int status_bar_width[STATUS_BAR_INDEX_MAX] = { 30, 200, 400, -1 };
#define BALL_MARGIN   10
// 状态栏第一列 状态灯， 第二列 操作状态及系统状态，第三列 系统信息， 四列  显示连接状态
customStatusBar::customStatusBar(QWidget *parent)
: QStatusBar(parent)
, thread_exit_flag(false)
, _bBallScal(false)
, status_bar_status(EAGLE_STATUS_BAR_NORMAL)
, m_pUiJob(new EaglePostEventManager(this))
, refresh_thread(&customStatusBar::threadJob_refreshStatus, this)
{
	m_statWgt = new QWidget(this);
	_statLabel_ball = new QLabel();
	_statLabel_stat = new QLabel(StatBarStatus[0]);
	_statLabel_info = new QLabel(tr(""));
	_statLabel_comm = new QLabel(tr(""));
 	_statLabel_ball->setFixedWidth(status_bar_width[STATUS_BAR_INDEX_NOPE]);
// 	_statLabel_stat->setFixedWidth(status_bar_width[STATUS_BAR_INDEX_STATUS]);
	_statLabel_info->setFixedWidth(status_bar_width[STATUS_BAR_INDEX_INFOR]);
	//_statLabel_info->setFixedWidth(this->fontMetrics().averageCharWidth() * 40);
	_statLabel_comm->setMinimumWidth(250);
	_statLabel_info->setWordWrap(true);
	
	QHBoxLayout*lay = new QHBoxLayout(m_statWgt);
	lay->setContentsMargins(2,0,6,0);  // 只保留右边边框
	lay->addWidget(_statLabel_ball);
	lay->addWidget(_statLabel_stat,1);
	addWidget(m_statWgt);
	addWidget(_statLabel_info);
	addWidget(_statLabel_comm,1);
	QPalette pe;
	pe.setColor(QPalette::WindowText, Qt::black); 
	_statLabel_stat->setPalette(pe);
	_statLabel_info->setPalette(pe);
	_statLabel_comm->setPalette(pe);
	QFont font = this->font();
	font.setPointSize(10);
	_statLabel_stat->setFont(font);
	_statLabel_info->setFont(font);
	_statLabel_comm->setFont(font);
	_statLabel_stat->setMinimumWidth(QFontMetrics(font).averageCharWidth() * 25);
	_statLabel_ball->setAlignment(Qt::AlignCenter);
	cycle_count = 0;
	_timer = new QTimer(this);
	connect(_timer, &QTimer::timeout, this, [this]
	{
		if (status_bar_status == EAGLE_STATUS_BAR_NORMAL)  
		{
			ECaptureStatusType status = GetCurrentSystemStatus(false);
			refresh_normal(status, CEagleDeviceMgr::GetInstance()->GetConnectionStatus());
		}
		else 
		{
			refresh_wait();
		}
		cycle_count++;
	});

	// 连接 info 日志消息
	//connect(g_theApp, &EagleMainFrame::evt_rawLog, this, &customStatusBar::on_FetchMsg);
	this->setFixedHeight(_statLabel_info->fontMetrics().height()*2 + 6);
	QTimer::singleShot(10, this, [this]()
	{
		_statLabel_ball->setFixedHeight(this->height());
		_image = QImage(this->height() - BALL_MARGIN, this->height() - BALL_MARGIN, QImage::Format_ARGB32);
		_image.fill(0);
		//qInfo() << m_statWgt->height() << ",LabeHeight:" << _statLabel_ball->height() << _image;
		_timer->setInterval(500);
		_timer->start();
	});
}

void customStatusBar::on_FetchMsg(int n, const QString& str)
{
	QMutexLocker lock(&m_Lock);

	m_strMsgList << str;
}

customStatusBar::~customStatusBar()
{
	thread_exit_flag = true;
	refresh_thread.join();
	_timer->stop();
}

void customStatusBar::SetStatusText(QString str, int index)
{
	switch (index)
	{
	case STATUS_BAR_INDEX_INFOR:
	{
		_statLabel_info->setText(str);
		break;
	}
	case STATUS_BAR_INDEX_STATUS:
	{
		_statLabel_stat->setText(str);
		break;
	}
	case STATUS_BAR_INDEX_CONMUNICATE_CHANNEL:
	{
		_statLabel_comm->setText(str);
		break;
	}
	default:
		break;
	}
}

void customStatusBar::refresh_normal(ECaptureStatusType status, bool connection_status)
{
	QColor disconnect_color = Qt::lightGray;
	QColor connect_color = Qt::green;
	QColor capture_color = Qt::red;
	QBrush disconnect_brush = QBrush(disconnect_color);
	QBrush connect_brush = QBrush(connect_color);
	QBrush capture_brush = QBrush(capture_color);
	QPen disconnect_pen = QPen(disconnect_color);
	QPen connect_pen = QPen(connect_color);
	QPen capture_pen = QPen(capture_color);

	QBrush *cur_brush = &disconnect_brush;
	QPen *cur_pen = &disconnect_pen;

	QString _msg = " ";
	if (connection_status)
	{
		if (status == ECaptureReady)
		{
			cur_brush = &connect_brush;
			cur_pen = &connect_pen;
		}
		else{
			cur_brush = &capture_brush;
			cur_pen = &capture_pen;
		}
		_msg = StatBarStatus.at(status + 1);
	}
	else
	{
		cur_brush = &disconnect_brush;
		cur_pen = &disconnect_pen;
		_msg = StatBarStatus.at(0);
	}
	// 状态栏 [11/21/2016 ejitec]
	_statLabel_stat->setText(_msg);
	//
	cur_pen->setWidth(1);
	_image.fill(0);
	QPainter painter(&_image);
	if (ECaptureTasking == status || ECapturePaused == status) 
	{
		painter.setBrush(*cur_brush);
		painter.setPen(*cur_pen);
	}
	else if (ECaptureRecording == status)
	{
		if (cycle_count % 2 == 0)
		{
			painter.setBrush(*cur_brush);
			painter.setPen(*cur_pen);
		}
		else
		{
			painter.setBrush(disconnect_brush);
			painter.setPen(disconnect_pen);
		}
	}
	else 
	{
		painter.setBrush(*cur_brush);
		painter.setPen(*cur_pen);
	} 
	painter.setRenderHint(QPainter::Antialiasing);
	painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
	QRect rec = _image.rect();
	painter.drawEllipse(rec.center(), rec.height() / 2 - 2, rec.height() / 2 - 2);
	_statLabel_ball->setPixmap(QPixmap::fromImage(_image));

}

void customStatusBar::refresh_wait()
{
	static QString dot = ".";

	QColor connect_color = Qt::green;
	QBrush connect_brush = QBrush(connect_color);
	QPen connect_pen = QPen(connect_color);
	QBrush *cur_brush = &connect_brush;
	QPen *cur_pen = &connect_pen;
	
	_image.fill(0);
	QPainter painter(&_image);
	painter.setBrush(connect_brush);
	connect_pen.setWidth(1);
	painter.setPen(connect_pen);
	painter.setRenderHint(QPainter::Antialiasing);
	painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
	QRect rec = _image.rect();
	painter.drawEllipse(rec.center(), rec.height()/2 - 2, rec.height()/2 - 2);
	_bBallScal ^= 0x1;

	if (dot == "...")
		dot = "";
	else
		dot += ".";
	//	PopStatusText(STATUS_BAR_INDEX_STATUS);
	//	PushStatusText(wait_msg + dot, STATUS_BAR_INDEX_STATUS);
	_statLabel_stat->setText(wait_msg + " " + dot);
	_statLabel_ball->setPixmap(QPixmap::fromImage(_image).scaledToHeight(
		_bBallScal ? rec.height(): rec.height()*2/3));
}

void customStatusBar::threadJob_refreshStatus()
{
	unsigned long long thread_cycle_count = 0;

	do
	{
		std::this_thread::sleep_for(std::chrono::milliseconds(1000));
		thread_cycle_count++;
		
		if (HaveNewEvents())
		{
			QMutexLocker locker(&m_Lock);
			QString str = m_strMsgList.first();
			m_strMsgList.removeFirst();
			
			m_pUiJob->Post([=]()
			{
				SetStatusText(str, STATUS_BAR_INDEX_INFOR);
			});
		}

		if (thread_cycle_count % 6 == 0)
		{
			long control_method = EagleConfigFile::getInstance()->conmunicate_method.toLong();
			if (control_method == CONTROL_SERIAL)
			{
				m_pUiJob->Post([this]() 
				{
					SetStatusText(EagleConfigFile::getInstance()->serial_port, STATUS_BAR_INDEX_CONMUNICATE_CHANNEL);
				});
			}
			else if (control_method == CONTROL_WINCAP)
			{
				QString status_text = QString("");
				QStringList eth_name = EagleConfigFile::getInstance()->eth_name;
					
				char dev_description[128] = { '\0' };
				std::vector<int> device_list;
				GetAllDevice(device_list);
				for (int it = 0; it != eth_name.size(); it++)
				{
					status_text += QString::fromUtf8("网卡 %1<--->").arg(it + 1);
					strcpy(dev_description, qPrintable(eth_name[it]));
					bool bFound = false;
					for (auto dev_it = device_list.begin(); dev_it != device_list.end(); dev_it++)
					{
						eagle_netcard_info netcard;
						EagleControl_GetCurrentControlNIC(*dev_it, &netcard);

						if (strcmp(netcard.dev_description, dev_description) == 0)
						{
							bFound = true;
							wchar_t name[64] = { '\0' };
							EagleControl_GetDeviceName(*dev_it, name);
							status_text += QString::fromWCharArray(name);
							status_text += ",";
						}
					}
					if (!bFound)
						status_text += QString::fromUtf8("未连接,");
				}
				if (!status_text.isEmpty())
				{
					if (status_text.endsWith(","))
					{
						status_text.chop(1);
					}

					m_pUiJob->Post([status_text, this]() 
					{
						SetStatusText(status_text, STATUS_BAR_INDEX_CONMUNICATE_CHANNEL);
					});
				}
			}
			else
			{
				m_pUiJob->Post([this]() 
				{
					SetStatusText("USB", STATUS_BAR_INDEX_CONMUNICATE_CHANNEL);
				});
			}
		}
	} while (!thread_exit_flag);
}

void customStatusBar::paintEvent(QPaintEvent *event)
{
	QStatusBar::paintEvent(event);

	QPainter painter(this);
	QPen pen = painter.pen();
	pen.setColor(Qt::darkGray);
	pen.setWidth(1);
	painter.setPen(pen);
	painter.drawLine(0,0,this->width(),0);
}


void customStatusBar::PushStatus(QString status)
{
	wait_msg = status;
	status_bar_status = EAGLE_STATUS_BAR_WAIT;
	last_msg = _statLabel_stat->text();
	SetStatusText(wait_msg, STATUS_BAR_INDEX_STATUS);
}
void customStatusBar::PopStatus()
{
	SetStatusText(last_msg, STATUS_BAR_INDEX_STATUS);
	status_bar_status = EAGLE_STATUS_BAR_NORMAL;
	
}
